package com.youdo.careyes.widget;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.youdo.careyes.R;
import com.youdo.careyes.utils.ToastUtil;
import com.youdo.careyes.utils.VideoFileSearcher;

import java.util.Objects;

public class MediaPlayerDialog extends Dialog {
    private final static float SCALE = 0.7f;
    protected Context mContext;
    private static final int PADDING = 20;
    private int mHeightPixels = 0;
    TextView tv_name;
    VideoView videoView;
    ImageView iv_pic;
    int type = 0;
    private int currentPosition = 0;

    public MediaPlayerDialog(@NonNull Context context, int type) {
        super(context, R.style.CustomDialog);
        mContext = context;
        this.type = type;
        setCancelable(false);
        initView();
    }

    private void initView() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_mediaplayer, null, false);
        setContentView(view);
        Window window = getWindow();
        final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
        mHeightPixels = displayMetrics.heightPixels;
        assert window != null;
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.gravity = Gravity.CENTER;
        attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
        if (window.getDecorView().getHeight() >= (int) (displayMetrics.heightPixels * SCALE)) {
            attributes.height = (int) (displayMetrics.heightPixels * SCALE);
        }
        Objects.requireNonNull(getWindow()).getDecorView().setPadding(PADDING, 0, PADDING, PADDING);
        window.setAttributes(attributes);
        tv_name = view.findViewById(R.id.tv_name);
        videoView = view.findViewById(R.id.video_view);
        iv_pic = view.findViewById(R.id.iv_pic);
        ViewGroup.LayoutParams params = iv_pic.getLayoutParams();
        // 设置ImageView的宽高为图片的实际宽高
        params.width = attributes.width;
        params.height = attributes.height;
        iv_pic.setLayoutParams(params);
        // 准备完成后自动播放
        videoView.setOnPreparedListener(mp -> videoView.start());

        // 播放完成后的回调
        videoView.setOnCompletionListener(mp -> {
            // 可以在这里处理播放完成逻辑，如返回列表页
            Log.e("youdo", "setOnCompletionListener");
            dismiss();
        });

        // 播放出错的回调
        videoView.setOnErrorListener((mp, what, extra) -> {
            // 处理播放错误，如提示用户视频损坏
            ToastUtil.showShort(R.string.play_err_tip);
            return true; // 返回true表示已处理错误
        });
    }

    public void showVideo(VideoFileSearcher.VideoInfo info) {
        if (info.isImage()) {
            videoView.setVisibility(View.GONE);
            iv_pic.setVisibility(View.VISIBLE);
            Glide.with(getContext())
                    .load(info.path)
                    .into(iv_pic);
        } else {
            videoView.setVisibility(View.VISIBLE);
            iv_pic.setVisibility(View.GONE);
            // 添加媒体控制器（包含播放/暂停、进度条、全屏等按钮）
            MediaController mediaController = new MediaController(getContext());
            // 设置控制器与VideoView关联
            videoView.setMediaController(mediaController);
            mediaController.setAnchorView(videoView);
            currentPosition = 0;
            videoView.setVideoPath(info.path);
            tv_name.setText(info.name);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
            if (videoView.isPlaying()) {
                videoView.pause();
                currentPosition = videoView.getCurrentPosition();
            } else {
                Log.e("youdo", "currentPosition = " + currentPosition);
                if (currentPosition > 0) {
                    videoView.seekTo(currentPosition);
                }
                videoView.start();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
